// node.js
const mume = require("@shd101wyy/mume");
const fs = require("fs");
const path = require('path')
const cheerio = require("cheerio");
const log4js = require("log4js");
log4js.configure("log4js.json");

// es6
// import * as mume from "@shd101wyy/mume"

async function mdParse(src,targerPath) {
  // const logger = log4js.getLogger('dev');
  const logger = log4js.getLogger();

  
  // if file exist
  if(!fs.existsSync(src)){
    logger.error('Source file ['+ src +'] is not exist.');
    return;
  }
  
  if(path.extname(src).toLowerCase() !== '.md'){
    logger.error('Source file ['+ src +'] is not a markdown file.');
    return;
  }
  
  if(!fs.existsSync(targerPath)){
    logger.error('Target path ['+ targerPath +'] is not exist.');
    return;
  }

  let hasErr = false;
  const htmlFile = path.join(path.dirname(src) , path.basename(src.toLowerCase(), '.md') + '.html');  
  const contentFile = path.join(targerPath, path.basename(src.toLowerCase(), '.md') + '-body.html')

  await mume.init();

  // new Markdown engine
  const engine = new mume.MarkdownEngine({
    filePath: src,
    config: {
      previewTheme: "atom-dark.css",
      codeBlockTheme: "atom-dark.css",
      printBackground: true,
      enableScriptExecution: true, // <= for running code chunks
    },
  });

  // html export  
  logger.debug(`Export markdown file [${ src }] to html ......`);
  await engine.htmlExport({ 
    
    // 是否离线？ true:使用本地Css文件  false:使用外链
    offline: false, 
    runAllCodeChunks: false 
  })
  .catch(function (err){    
    logger.error(err);
    hasErr =true;
  });

  if(hasErr) return;

  // Load html file
  logger.debug(`Load html file [${htmlFile}] ......`);
  const myHtml = fs.readFileSync(htmlFile);
  const $ = cheerio.load(myHtml);

  const $bodyContent = $('body .markdown-preview');
  
  // save article body 
  logger.debug(`Save content html to target file [${contentFile}] ......`);
  fs.writeFileSync(contentFile, $bodyContent.eq(0).html(), function(err) {
    if (err) {
      hasErr =true;
      logger.error(err);
    }
  });

  if(hasErr) return;

  // get title
  logger.debug(`Get the article title & preview ......`);
  const title = $bodyContent.children().eq(0).text().trim();
  // todo: save title to DB
  
  // get preview content
  $bodyContent.children().eq(0).remove();

  // Replace the line terminator with <br>, need save to DB
  const previewConrent = $bodyContent.text().trim().substr(0,200).replace(/$/mg,"<br>");
  // todo: save preview content to DB

  
  logger.debug(`Save information of the article to DB ......`);

  // delete html file
  logger.debug(`Delete intermediate file [${ htmlFile }] ......`);
 // fs.unlinkSync(htmlFile);

  return process.exit();
}

mdParse('/media/houjk/data/hjklib/js/self/理解箭头函数中的this.md','/media/houjk/data/hjklib/js/');